<template>
    <div class="wrap">
        <div id="container">
            <!-- 定义一个表格元素 -->
            <section class="detail-header">
                <div class="col-sm-12 console-title">
                    <h5 class="">模块异常告警</h5>
                    <div class="stayRight ">
                      <el-button @click="setConfig()">默认告警设置</el-button>
                    </div>
                </div>
            </section>
            <section class="searchBar">
                <div class="form-inline">
                    <div class="pull-left">
                        <div class="searchIpt">
                            <el-input  v-model="domains.searchDomain" placeholder="请输入模块名称进行搜索" :trigger-on-focus="false" class="searchIpt1"></el-input>
                        </div>
                        <div class="searchbtn">
                            <el-button @click="getDomains(1)">搜索</el-button>
                        </div>
                    </div>
                </div>
            </section>
            <section class="tableMain">
                <el-table :data="domains.dataArr"  border style="width: 100%"  >
                    <el-table-column label="模块名称" prop="name" ></el-table-column>
                    <el-table-column label="告警设置"> 
                      <template scope="scope">
                        <el-button type="primary"  size="small" @click="setAlarmContact(scope.row)">联系人设置</el-button>
                        <el-button type="primary"  size="small" @click="setExceptionAlarm(scope.row)">明细设置</el-button>
                      </template>
                    </el-table-column>
                </el-table>
                <div class="pageSIzeblock">
                    <div class="pullright">
                        <el-pagination @size-change="domainsHandleSizeChange"  @current-change="domainsHandleCurrentChange" :current-page="domains.currPage" :page-sizes="[10, 20, 50, 100]" :page-size="domains.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="domains.totalCount">
                        </el-pagination>
                    </div>
                </div>
            </section>

            <el-dialog title="默认告警设置" :visible.sync="configDialogVislble" class="customDialog team" :lock-scroll="false" size="small">
                <div class="scoreContainer tagCategory">
                    <el-form :model="configUpdateForm" :rules="configUpdateRules" ref="configUpdateForm" label-width="120px" class="demo-updateForm">
                        <el-form-item label="告警频率" prop="freq">
                          <el-select v-model="configUpdateForm.freq" placeholder="请选择">
                            <el-option
                              v-for="item in alarmConfig.freqs"
                              :key="item.key"
                              :value="item.key"
                              :label="item.label">
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="告警阈值" prop="threshold">
                          <el-input v-model="configUpdateForm.threshold" type="number" min="1" max="100000"></el-input>
                        </el-form-item>

                        <el-form-item label="白名单">
                            <el-transfer 
                              filterable
                             :footer-format="{
                                noChecked: '共${total}项',
                                hasChecked: '已选${checked}/${total} 项'
                              }"
                             :titles="['未选模块', '已选模块']"  
                             v-model="configUpdateForm.whites" 
                             :data="alarmConfig.domains"> 
                            </el-transfer>
                        </el-form-item>

                        <el-form-item label="通知对象">
                            <el-transfer 
                              filterable
                             :footer-format="{
                                noChecked: '共${total}项',
                                hasChecked: '已选${checked}/${total} 项'
                              }"
                             :titles="['未选联系人组', '已选联系人组']"  
                             v-model="configUpdateForm.contactIds" 
                             :data="contacts.dataArr"> 
                            </el-transfer>
                        </el-form-item>


                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <div class="aar-gap">
                        <div class="aar-gap-line-b">
                            <div class="aar-gap-line"></div>
                        </div>
                    </div>
                  <el-button type="primary" @click="configSubmit('configUpdateForm')">确 定</el-button>
                </span>
            </el-dialog>


            <el-dialog title="告警联系人设置" :visible.sync="alarmContactDialogVislble" class="customDialog team" :lock-scroll="false" size="small">
                <div class="scoreContainer tagCategory">
                    <el-form :model="alarmContactUpdateForm" :rules="alarmContactUpdateRules" ref="alarmContactUpdateForm" label-width="120px" class="demo-updateForm">
                        <el-form-item label="模块名称" prop="domain">
                          {{alarmContactUpdateForm.domain}}
                        </el-form-item>

                        <el-form-item label="通知对象">
                            <el-transfer 
                              filterable
                             :footer-format="{
                                noChecked: '共${total}项',
                                hasChecked: '已选${checked}/${total} 项'
                              }"
                             :titles="['未选联系人组', '已选联系人组']"  
                             v-model="alarmContactUpdateForm.contactIds" 
                             :data="contacts.dataArr"> 
                            </el-transfer>
                        </el-form-item>

                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <div class="aar-gap">
                        <div class="aar-gap-line-b">
                            <div class="aar-gap-line"></div>
                        </div>
                    </div>
                  <el-button type="primary" @click="alarmContactSubmit('alarmContactUpdateForm')">确 定</el-button>
                </span>
            </el-dialog>


            
            <el-dialog title="模块异常列表" :visible.sync="exceptionAlarmDialogVislble" class="customDialog team" :lock-scroll="false" size="full" >
                <div class="scoreContainer tagCategory">
                  <section class="searchBar">
                      <div class="form-inline">
                          <div class="pull-left">
                              <div class="searchIpt">
                                  <el-input  v-model="exceptions.searchException" placeholder="请输入异常进行搜索" :trigger-on-focus="false" class="searchIpt1"></el-input>
                              </div>
                              <div class="searchbtn">
                                  <el-button @click="getExceptions(1)">搜索</el-button>
                              </div>
                          </div>
                      </div>
                  </section>
                  <section class="tableMain">
                      <el-table :data="exceptions.dataArr" border style="width: 100%"  @sort-change="exceptionsHandleSortChange">
                          <el-table-column prop="exception" label="异常" width="500"> </el-table-column>
                          <el-table-column prop="domain" label="所属模块" width="180"> </el-table-column>
                          <el-table-column prop="errCnt" label="本月上报次数" sortable="custom" width="180"> </el-table-column>
                          <el-table-column prop="addTime" sortable="custom" label="录入时间" :formatter="formatTime" width="180"> </el-table-column>
                          <el-table-column prop="freq" label="告警频率" :formatter="formatFreq"> </el-table-column>
                          <el-table-column prop="threshold" label="告警阈值"> </el-table-column>
                          <el-table-column prop="white" label="是否白名单" :formatter="formatWhite">
                          </el-table-column>
                          <el-table-column label="告警设置"> 
                            <template scope="scope">
                              <el-button type="primary"  size="small" @click="setExceptionItem(scope.row)">设置</el-button>
                            </template>
                          </el-table-column>
                      </el-table>
                      <div class="pageSIzeblock">
                          <div class="pullright">
                              <el-pagination @size-change="exceptionsHandleSizeChange"  @current-change="exceptionsHandleCurrentChange" :current-page="exceptions.currPage" :page-sizes="[10, 20, 50, 100]" :page-size="exceptions.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="exceptions.totalCount">
                              </el-pagination>
                          </div>
                      </div>
                  </section>
                </div>
            </el-dialog>

            <el-dialog title="告警详情设置" :visible.sync="exceptionDetailDialogVislble" class="customDialog team" :lock-scroll="false" size="tiny">
                <div class="scoreContainer tagCategory">
                    <el-form :model="exceptionDetailUpdateForm" :rules="configUpdateRules" ref="exceptionDetailUpdateForm" label-width="120px" class="demo-updateForm">
                        <el-form-item label="告警频率" prop="freq">
                          <el-select v-model="exceptionDetailUpdateForm.freq" placeholder="请选择">
                            <el-option
                              v-for="item in alarmConfig.freqs"
                              :key="item.key"
                              :value="item.key"
                              :label="item.label">
                            </el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="告警阈值" prop="threshold">
                          <el-input v-model="exceptionDetailUpdateForm.threshold" type="number" min="1" max="100000"></el-input>
                        </el-form-item>

                        <el-form-item label="是否白名单" prop="white">
                          <el-select v-model="exceptionDetailUpdateForm.white" placeholder="请选择">
                            <el-option
                              v-for="item in alarmConfig.truns"
                              :key="item.key"
                              :value="item.key"
                              :label="item.label">
                            </el-option>
                          </el-select>
                        </el-form-item>

                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <div class="aar-gap">
                        <div class="aar-gap-line-b">
                            <div class="aar-gap-line"></div>
                        </div>
                    </div>
                  <el-button type="primary" @click="exceptionSubmit('exceptionDetailUpdateForm')">确 定</el-button>
                </span>
            </el-dialog>


        </div>
    </div>
</template>
<script>
import { queryAlarmDefaultConfig, updateAlarmDefaultConfig, queryDomains, updateDomainContact, queryExceptions, updateExceptionItem, queryDomainNames } from '@/api/domainExceptionData'
import { getAlarmContactsGroupList } from '@/api/alarmRulesData'
import { parseTime } from '@/utils/index'
import { Loading } from 'element-ui'
export default {
  data() {
    return {
      domains: {
        dataArr: [],
        searchDomain: '',
        currPage: 1,
        pageSize: 10,
        totalCount: 0
      },
      contacts: {
        dataArr: []
      },
      alarmConfig: {
        freq: 0,
        threshold: 0,
        contactIds: [],
        freqs: [
          { key: 1, label: '1分钟' },
          { key: 3, label: '3分钟' },
          { key: 5, label: '5分钟' }
        ],
        truns: [
          { key: 0, label: '否' },
          { key: 1, label: '是' }
        ],
        whites: [],
        domains: []
      },
      configDialogVislble: false,
      configUpdateForm: {
        freq: 0,
        threshold: 0,
        contactIds: [],
        whites: []
      },
      configUpdateRules: {
        freq: [
          { validator: this.checkFreq, trigger: 'blur' }
        ],
        threshold: [
          { validator: this.checkThreshold, trigger: 'blur' }
        ]
      },
      alarmContactDialogVislble: false,
      alarmContactUpdateForm: {
        domainId: 0,
        domain: 0,
        contactIds: []
      },
      alarmContactUpdateRules: {
      },
      exceptionAlarmDialogVislble: false,
      exceptions: {
        domain: '',
        dataArr: [],
        searchException: '',
        currPage: 1,
        pageSize: 10,
        totalCount: 0,
        prop: '',
        order: ''
      },
      exceptionDetailDialogVislble: false,
      exceptionDetailUpdateForm: {
        id: 0,
        freq: 0,
        threshold: 0,
        white: 0
      }
    }
  },
  created() {
    this.getDomains(1)
    this.getDomainList()
    this.getContacts()
    this.getAlarmDefaultConfig()
  },
  methods: {
    refreshData() {
      this.exceptions.searchException = ''
      this.getDomains(1)
      this.getDomainList()
      this.getContacts()
      this.getAlarmDefaultConfig()
    },
    getDomains(currPage) {
      this.domains.currPage = currPage
      var loadId = Loading.service({ text: '加载中，请稍等' })
      var listQuery = { keyword: this.domains.searchDomain, currPage: this.domains.currPage, pageSize: this.domains.pageSize }
      queryDomains(listQuery).then(response => {
        console.log(response)
        this.domains.dataArr = response.data.page.list
        this.domains.totalCount = response.data.page.totalCount
        loadId.close()
      }).catch(_ => {
        loadId.close()
      })
    },
    getDomainList() {
      this.alarmConfig.domains = []
      queryDomainNames().then(response => {
        console.log(response.data)
        response.data.rows.forEach(function(element) {
          this.alarmConfig.domains.push({
            key: element,
            label: element
          })
        }, this)
      }).catch(_ => {
      })
    },
    getContacts() {
      this.contacts.dataArr = []
      getAlarmContactsGroupList().then(response => {
        response.data.data.forEach(function(element) {
          this.contacts.dataArr.push({
            key: element.id,
            label: element.name
          })
        }, this)
      }).catch(_ => {
      })
    },
    getAlarmDefaultConfig() {
      queryAlarmDefaultConfig().then(response => {
        this.alarmConfig.freq = response.data.alarmConfig.freq
        this.alarmConfig.threshold = response.data.alarmConfig.threshold
        this.alarmConfig.contactIds = response.data.alarmConfig.contactIds
        this.alarmConfig.whites = response.data.alarmConfig.whites
      }).catch(_ => {
      })
    },
    getExceptions(currPage) {
      this.exceptions.currPage = currPage
      var loadId = Loading.service({ text: '加载中，请稍等' })
      var listQuery = { domain: this.exceptions.domain, keyword: this.exceptions.searchException, currPage: this.exceptions.currPage, pageSize: this.exceptions.pageSize, prop: this.exceptions.prop, order: this.exceptions.order }
      queryExceptions(listQuery).then(response => {
        console.log(response)
        this.exceptions.dataArr = response.data.page.list
        this.exceptions.totalCount = response.data.page.totalCount
        loadId.close()
      }).catch(_ => {
        loadId.close()
      })
    },
    setConfig() {
      this.configUpdateForm = JSON.parse(JSON.stringify(this.alarmConfig))
      this.configDialogVislble = true
    },
    setAlarmContact(item) {
      this.alarmContactUpdateForm = {
        domainId: item.id,
        domain: item.name,
        contactIds: item.contactIds
      }
      this.alarmContactDialogVislble = true
    },
    setExceptionAlarm(item) {
      this.exceptions.domain = item.name
      this.exceptions.searchException = ''
      this.getExceptions(1)
      this.exceptionAlarmDialogVislble = true
    },
    setExceptionItem(item) {
      this.exceptionDetailUpdateForm = JSON.parse(JSON.stringify(item))
      this.exceptionDetailDialogVislble = true
    },
    formatTime(row, column) {
      if (row.addTime) {
        return parseTime(row.addTime)
      }
      return ''
    },
    formatFreq(row, column) {
      if (row.freq) {
        return row.freq + '分钟'
      }
      return ''
    },
    formatWhite(row, column) {
      if (row.white) {
        return '是'
      }
      return '否'
    },
    checkFreq(rule, value, callback) {
      if (!value) {
        callback(new Error('请选择频率'))
      } else {
        callback()
      }
    },
    checkThreshold(rule, value, callback) {
      if (!value || value < 1 || value > 100000) {
        callback(new Error('阈值区间为1-100000'))
      } else {
        callback()
      }
    },
    domainsHandleSizeChange(pageSize) {
      this.domains.pageSize = pageSize
      this.getDomains(1)
    },
    domainsHandleCurrentChange(currPage) {
      this.domains.currPage = currPage
      this.getDomains(currPage)
    },
    exceptionsHandleSortChange(sort) {
      console.log(sort)
      this.exceptions.prop = sort.prop
      this.exceptions.order = sort.order
      if (this.exceptions.order) {
        this.exceptions.order = sort.order.startsWith('asc') ? 'asc' : 'desc'
      }
      this.getExceptions(1)
    },
    exceptionsHandleSizeChange(pageSize) {
      this.exceptions.pageSize = pageSize
      this.getExceptions(1)
    },
    exceptionsHandleCurrentChange(currPage) {
      this.exceptions.currPage = currPage
      this.getExceptions(currPage)
    },
    configSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var loadId = Loading.service({ text: '正在保存' })
          var jsonData = {}
          jsonData.freq = this.configUpdateForm.freq
          jsonData.threshold = this.configUpdateForm.threshold
          jsonData.contactId = this.configUpdateForm.contactIds.join(',')
          jsonData.white = this.configUpdateForm.whites.join(',')
          var _this = this
          const resetTable = function() {
            _this.configDialogVislble = false
            _this.getAlarmDefaultConfig()
          }
          updateAlarmDefaultConfig(jsonData).then(response => {
            loadId.close()
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            })
            resetTable()
          }).catch(_ => {
            loadId.close()
          })
        }
      })
    },
    alarmContactSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var loadId = Loading.service({ text: '正在保存' })
          var jsonData = this.alarmContactUpdateForm
          var _this = this
          const resetTable = function() {
            _this.alarmContactDialogVislble = false
            _this.getDomains()
          }
          updateDomainContact(jsonData).then(response => {
            loadId.close()
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            })
            resetTable()
          }).catch(_ => {
            loadId.close()
          })
        }
      })
    },
    exceptionSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var loadId = Loading.service({ text: '正在保存' })
          var jsonData = {}
          jsonData.id = this.exceptionDetailUpdateForm.id
          jsonData.freq = this.exceptionDetailUpdateForm.freq
          jsonData.threshold = this.exceptionDetailUpdateForm.threshold
          jsonData.white = this.exceptionDetailUpdateForm.white
          var _this = this
          const resetTable = function() {
            _this.exceptionDetailDialogVislble = false
            _this.getExceptions(1)
          }
          updateExceptionItem(jsonData).then(response => {
            loadId.close()
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            })
            resetTable()
          }).catch(_ => {
            loadId.close()
          })
        }
      })
    }
  }
}
</script>


<style lang="scss">
.el-table .warning-row {
    background: #dd9999;
}
.el-table .info-row {
    background: #c9e5f5;
}
.detail-header{
    padding: 0 15px;
    margin-bottom: 10px;
    overflow: hidden;
    .console-title{
        padding: 16px 0px;
        min-height: 70px;
        border-bottom: 1px solid #eee;
        position: relative;
        h5{
            display: inline-block;
            text-indent: 8px;
            border-left: 2px solid #88B7E0;
            margin: 8px 0;
            margin-right: 8px;
            vertical-align: top;
        }
        .stayRight{
            position: absolute;
            top: 15px;
            right: 0;
            overflow: hidden;
            .refresh{
                float: left;
                margin-right: 10px;
                color: #333;
                border: 1px solid #ddd;
                background-color: #F7F7F7;
            }
            .creatSite{
                float: left;
            }
        }
    }
}
.searchSel{
    width: 105px;
    display: inline-block;
}
.searchIpt{
    width: 650px;
    margin: 10px 0px;
    display: inline-block;
}
.searchIpt1{
  width:100%;
}
.searchbtn{
    width: 100px;
    display: inline-block;
}
.searchBar{
    padding: 0 10px;
}
.typeform{
    display: inline;
    .form-control{
        border: none;
        padding: 0;
        box-shadow:none;
        display: inline;
        height:30px;
        width:60%;
    }
}
.spantype{
    display: inline;
}
.pageSIzeblock{
    overflow: hidden;
    padding: 10px 0;
    .pullright{
        float: right;
    }
}
.tableMain{
    padding: 10px;
}
.el-table__expanded-cell{padding: 0px 0px;}
.instanceTypeClass .el-select{width:800px;}
.delBtn{font-weight:bold;font-size:13px;position:absolute;right:0px;top:8px;background:#fff;}
</style>


